<?php
defined('IN_XLP') || exit('Access Denied');

/*
 * 财务相关
 */
class financeAction extends commonAction {

    function __construct() {
        parent::__construct();
        parent::_checkLogin();
        G('path_mod', 2);
    }

    public function chart() {
        $page       = empty($_GET['page']) ? 1 : intval($_GET['page']);
        $limit      = ($page - 1)*20;
        $starttime  = empty($_GET['starttime']) ? null : $_GET['starttime'];
        $endtime    = empty($_GET['endtime']) ? null : $_GET['endtime'];

        $where = ' 1=1 ';
        if($starttime) $where .= " AND o.`payment_time`>=".strtotime($starttime);
        if($endtime) $where .= " AND o.`payment_time`<=".strtotime($endtime);

        $where .= " AND o.`payment_time`<>0 AND o.`id`=og.`order_id` ";

        $sql = "SELECT o.`id`,o.`order_sn`,o.`shipping_fee`,o.`order_amount`,o.`score_used`,o.`refund_shipping`,o.`actual_refund` AS o_ar,o.`score_return`,o.`user_id`,o.`payment_time`,
                og.`goods_id`,og.`goods_name`,og.`goods_price`,og.`goods_num`,og.`actual_refund` AS og_ar,og.`actual_return`,og.`score`,og.`score_minus`
                FROM __PRE__order o, __PRE__order_goods og
                WHERE $where
                ORDER BY o.`payment_time` DESC";

        if(!isset($_GET['export'])) {
            $sql .= " LIMIT $limit,20 ";
        }

        $goods_list = M()->query($sql);

        foreach ($goods_list as $k => $v) {
            $goods_list[$k]['actual_pay'] = priceFormat($v['order_amount'] - $v['score_used']/100);
        }

        //导出订单
        if(isset($_GET['export']) && $_GET['export']==1) {
            $this->chart_export($goods_list);
            exit;
        }

        $sql = "SELECT og.`id` FROM __PRE__order o,__PRE__order_goods og WHERE $where";
        $total = M()->query($sql);
        $total = count($total);

        

        //起始时间
        $this->assign('starttime', $starttime);
        $this->assign('endtime', $endtime);
        //页码
        $this->assign('page', $page);
        //商品列表
        $this->assign('list', $goods_list);
        //订单总数
        $this->assign('total', $total);
        $this->display();
    }


    public function refund_chart() {
        $page       = empty($_GET['page']) ? 1 : intval($_GET['page']);
        $limit      = ($page - 1)*20;
        $starttime  = empty($_GET['starttime']) ? null : $_GET['starttime'];
        $endtime    = empty($_GET['endtime']) ? null : $_GET['endtime'];
        // $searchtype = isset($_GET['searchtype']) ? intval($_GET['searchtype']) : null;
        // $keyword    = empty($_GET['keyword']) ? null : trim($_GET['keyword']);

        $where = ' r.`finance_time`<>0 ';
        if(isset($starttime)) {
            $where .= ' AND r.`finance_time`>= '.strtotime($starttime);
        }
        if(isset($endtime)) {
            $where .= ' AND r.`finance_time`<= '.strtotime($endtime);
        }

        $sql = "SELECT r.`order_id`,r.`order_sn`,r.`user_id`,r.`recipient`,r.`actual_refund`,r.`actual_return`,r.`finance_time`,
                o.`refund_shipping`,o.`score_return`
                FROM __PRE__order o,__PRE__return_log r
                WHERE $where
                AND r.`order_id`=o.`id`
                ORDER BY r.`finance_time` DESC";

        if(!isset($_GET['export'])) {
            $sql .= " LIMIT $limit,20 ";
        }
        //退款列表
        $refund_list = M()->query($sql);


        //导出订单
        if(isset($_GET['export']) && $_GET['export']==1) {
            $this->refund_chart_export($refund_list);
            exit;
        }

        // z($refund_list);
        $sql = "SELECT r.`id` FROM __PRE__return_log r WHERE $where";
        $total = M()->query($sql);
        $refund_total = count($total);

        //起始时间
        $this->assign('starttime', $starttime);
        $this->assign('endtime', $endtime);
        //订单状态
        // $this->assign('status', $status);
        //页码
        $this->assign('page', $page);
        //订单列表
        $this->assign('list', $refund_list);
        //订单总数
        $this->assign('total', $refund_total);
        $this->display();
    }

    /*
     * 导出财务报表
     */
    private function chart_export($data) {
        $goods_list    = array();
        $finance_title = array('订单ID','订单号','货号','商品名称','单价','购买数量','运费','订单总价','使用结邻币','实付','奖励结邻币','用户UID','付款日期','');
        //'返还结邻币','扣除结邻币',//'商品退款','运费退款','退款总额','退货数量',

        $income_total = 0;
        $outcome_total = 0;
        $income_coin_total = 0;
        $outcome_coin_total = 0;

        //查询商品货号
        $goods_id_arr = array();
        foreach ($data as $v) {
            $goods_id_arr[] = $v['goods_id'];
        }
        $goods_ids = implode(',', $goods_id_arr);
        if(empty($goods_ids)) $goods_ids = 0;

        $result = M('goods')
            ->field("`id`,`goods_sn`")
            ->where("`id` in ($goods_ids)")
            ->findAll();

        if(empty($result)) {
            exit('没有数据');
        }

        $temp_arr = array();
        foreach ($result as $v) {
            $temp_arr[$v['id']] = $v['goods_sn'];
        }

        foreach ($data as $k => $v) {
            $data[$k]['goods_sn'] = $temp_arr[$v['goods_id']];
        }

        foreach ($data as $k => $v) {
            $goods_list[] = array(
                'id'              => $v['id'],
                'order_sn'        => "\t".$v['order_sn'],
                'goods_sn'        => $v['goods_sn'],
                'goods_name'      => $v['goods_name'],
                'goods_price'     => $v['goods_price'],
                'goods_num'       => $v['goods_num'],
                'shipping_fee'    => $v['shipping_fee'],
                'order_amount'    => $v['order_amount'],
                'score_used'      => $v['score_used'],
                'actual_pay'      => $v['actual_pay'],
                // 'og_ar'           => $v['og_ar'],
                // 'refund_shipping' => $v['refund_shipping'],
                // 'o_ar'            => $v['o_ar'],
                // 'actual_return'   => $v['actual_return'],
                // 'score_return'    => "\t".$v['score_return'],
                'score'           => $v['score'],
                // 'score_minus'     => "\t".$v['score_minus'],
                'user_id'         => $v['user_id'],
                'payment_day'     => "\t".date('Y-m-d', $v['payment_time']),
                'payment_time'    => "\t".date('H:i:s', $v['payment_time']),
            );
            $income_total  += $v['actual_pay'];
            $outcome_total += $v['o_ar'];
            $income_coin_total += $v['score_used'];
        }

        $income_total  = priceFormat($income_total);
        $outcome_total = priceFormat($outcome_total);
        $income_coin_total = priceFormat($income_coin_total);

        $goods_list = array_reverse($goods_list);

        $goods_list[] = array('合计','','','','','','','','',
            '收入总计:'.$income_total,'','','支出总计:'.$outcome_total,
            '','使用结邻币:'.$income_coin_total);

        load('csv');
        $csv = new csv();
        $csv->write($finance_title, $goods_list, "报表".date('Y-m-d'));
    }

    /*
     * 导出退款报表
     */
    public function refund_chart_export($data) {
        $refund_title = array('订单ID','订单号','用户UID','收货人','退款金额','退货数量','退还运费','退还结邻币','退款时间');

        $refund_list = array();
        foreach ($data as $k => $v) {
            $refund_list[] = array(
                'order_id'        => $v['order_id'],
                'order_sn'        => "\t".$v['order_sn'],
                'uid'             => $v['user_id'],
                'recipient'       => $v['recipient'],
                'actual_refund'   => $v['actual_refund'],
                'actual_return'   => $v['actual_return'],
                'refund_shipping' => $v['refund_shipping'],
                'score_return'    => $v['score_return'],
                'finance_time'    => "\t".date('Y-m-d', $v['finance_time']),
            );
        }

        load('csv');
        $csv = new csv();
        $csv->write($refund_title, $refund_list, "退款报表".date('Y-m-d'));   
    }

    public function refund() {
        $page       = empty($_GET['page']) ? 1 : intval($_GET['page']);
        $limit      = ($page - 1)*20;
        $starttime  = empty($_GET['starttime']) ? null : $_GET['starttime'];
        $endtime    = empty($_GET['endtime']) ? null : $_GET['endtime'];
        // $searchtype = isset($_GET['searchtype']) ? intval($_GET['searchtype']) : null;
        // $keyword    = empty($_GET['keyword']) ? null : trim($_GET['keyword']);

        $where = '';
        if(isset($starttime)) {
            $where .= " `return_time`>= ".strtotime($starttime);
        }
        if(isset($endtime)) {
            if($where) {
                $where .= " AND `return_time`<= ".strtotime($endtime);
            } else {
                $where .= " `return_time`<= ".strtotime($endtime);
            }
        }

        //退款列表
        $refund_list = M('return_log')
                ->where($where)
                ->limit($limit,20)
                ->order('`return_time` DESC')
                ->select();
        //退款订单总数
        $refund_total = M('return_log')->getTotal();
        // z($refund_list);
        
        //退款OR退货商品
        $order_ids = array();
        foreach ($refund_list as $v) {
            $order_ids[] = $v['order_id'];
        }
        $order_ids = implode(',', $order_ids);
        if(empty($order_ids)) $order_ids = 0;

        $sql = "SELECT o.`id`,o.`goods_amount`,o.`shipping_fee`,o.`score_used`,
                og.`goods_name`,og.`goods_price`,og.`goods_num`,og.`goods_refund`,og.`goods_returnnum`,og.`score`
                FROM __PRE__order o, __PRE__order_goods og
                WHERE o.`id` in ($order_ids)
                AND o.`id`=og.`order_id`";

        // z($sql);
        $refund_goods = M()->query($sql);
        // z($refund_orders);

        //合并商品到退款订单
        foreach ($refund_list as $k => $v) {
            //申请时间 客服处理时间 财务处理时间
            $refund_list[$k]['return_time'] = date("Y-m-d H:i:s", $v['return_time']);
            if($v['service_time']) {
                $refund_list[$k]['service_time'] = date("Y-m-d H:i:s", $v['service_time']);
            } else {
                $refund_list[$k]['service_time'] = '';
            }
            if($v['finance_time']) {
                $refund_list[$k]['finance_time'] = date("Y-m-d H:i:s", $v['finance_time']);
            } else {
                $refund_list[$k]['finance_time'] = '';
            }

            //退款按钮URL
            $refund_url = U('content/finance/refund_form',array('order_id'=>$v['order_id']));
            //退款详情URL
            $refund_info_url = U('content/finance/refund_info',array('order_id'=>$v['order_id']));

            //状态
            $refund_list[$k]['refund_state_code'] = $refund_list[$k]['refund_state'];
            switch ($refund_list[$k]['refund_state']) {
                case '1':
                    $refund_list[$k]['refund_state'] = '<span style="color:blue">买家申请退款</span>';
                    $refund_list[$k]['refund_btn'] = '<a href="'.$refund_url.'" class="info_btn" rel="pop">查看</a>';
                    break;
                case '2':
                    $refund_list[$k]['refund_state'] = '<span style="color:red">客服同意退款</span>';
                    if($v['order_return']>0){
                        $refund_list[$k]['refund_btn'] = '<a href="'.$refund_url.'" class="refund_btn" rel="pop">退货退款</a>';
                    } else {
                        $refund_list[$k]['refund_btn'] = '<a href="'.$refund_url.'" class="refund_btn" rel="pop">退款</a>';                        
                    }
                    break;
                case '3':
                    $refund_list[$k]['refund_state'] = '<span style="color:black">客服拒绝退款</span>';
                    $refund_list[$k]['refund_btn'] = '<a href="'.$refund_url.'" class="info_btn" rel="pop">查看</a>';
                    break;
                case '4':
                    $refund_list[$k]['refund_state'] = '<span style="color:#15a230">已退款</span>';
                    $refund_list[$k]['refund_btn'] = '<a href="'.$refund_info_url.'" class="info_btn" rel="pop">查看</a>';
                    break;
                default:
                    $refund_list[$k]['refund_state'] = 'unknown';
                    break;
            }

            foreach ($refund_goods as $key => $value) {
                if($value['id']==$v['order_id']) {
                    $refund_list[$k]['goods_amount']   = $refund_goods[$key]['goods_amount'];     //商品总价(不含运费)
                    $refund_list[$k]['shipping_fee']   = $refund_goods[$key]['shipping_fee'];     //订单运费
                    $refund_list[$k]['score_used']     = $refund_goods[$key]['score_used'];       //订单使用结邻币
                    $refund_list[$k]['actual_pay']     = priceFormat($refund_list[$k]['order_amount'] - $refund_goods[$key]['score_used']/100);   //实付
                    $refund_list[$k]['refund_goods'][] = array(
                        'goods_name'      => $refund_goods[$key]['goods_name'],     //商品名称
                        'goods_price'     => $refund_goods[$key]['goods_price'],    //商品售价
                        'goods_num'       => $refund_goods[$key]['goods_num'],      //商品数量
                        'goods_refund'    => $refund_goods[$key]['goods_refund'],   //申请退款金额
                        'goods_returnnum' => $refund_goods[$key]['goods_returnnum'],//申请退货数量
                        'score'           => $refund_goods[$key]['score'],          //商品赠送结邻币
                    );
                    unset($refund_goods[$key]);
                }
            }
        }
        // z($refund_list);

        //起始时间
        $this->assign('starttime', $starttime);
        $this->assign('endtime', $endtime);
        //订单状态
        // $this->assign('status', $status);
        //页码
        $this->assign('page', $page);
        //订单列表
        $this->assign('list', $refund_list);
        //订单总数
        $this->assign('total', $refund_total);
        $this->display();
    }

    /*
     * 财务退款表单
     */
    public function refund_form() {

        $order_id = $this->_getid('order_id');
        $refund   = M('return_log')->where(array('order_id'=>$order_id))->find();
        // z($refund);
        
        //退款订单
        $order_info = M('order')
            ->field('`shipping_fee`,`score_used`,`goods_amount`,`order_amount`,`refund_amount`')
            ->where(array('id'=>$order_id))
            ->find();

        //实付
        $order_info['actual_pay'] = priceFormat($order_info['order_amount'] - $order_info['score_used']/100);

        //按退款比例退还结邻币
        $refund_coin = floor($order_info['refund_amount']/$order_info['goods_amount']*$order_info['score_used']);

        //退款商品
        $order_goods = M('order_goods')
            ->field('`id`,`goods_id`,`goods_name`,`goods_price`,`goods_num`,`goods_refund`,`goods_returnnum`,`score`')
            ->where(" `order_id`=$order_id AND `goods_refund`>0 ")
            ->findAll();

        //按退款退货数量扣除结邻币
        foreach ($order_goods as $k=>$v) {
            $order_goods[$k]['score_minus'] = 
                $v['goods_returnnum'] ? floor($v['goods_returnnum']/$v['goods_num']*$v['score']) : $v['score'];
        }

        
        $this->assign('refund', $refund);
        $this->assign('order_info', $order_info);
        $this->assign('order_goods', $order_goods);
        $this->assign('refund_coin', $refund_coin);
        $this->display();
    }

    /*
     * 退款订单详情
     */
    public function refund_info() {
        $order_id = $this->_getid('order_id');
        $refund   = M('return_log')->where(array('order_id'=>$order_id))->find();

        //退款订单
        $order_info = M('order')
            ->field('`actual_refund`,`refund_shipping`,`shipping_fee`,`score_used`,`score_return`,`goods_amount`,`order_amount`')
            ->where(array('id'=>$order_id))
            ->find();
        //实付
        $order_info['actual_pay'] = priceFormat($order_info['order_amount'] - $order_info['score_used']/100);

        //退款商品
        $order_goods = M('order_goods')
            ->field('`id`,`goods_id`,`goods_name`,`goods_price`,`goods_num`,`goods_refund`,`goods_returnnum`,`score`,`score_minus`,`actual_refund`,`actual_return`')
            ->where(" `order_id`=$order_id AND `goods_refund`>0 ")
            ->findAll();


        $this->assign('refund', $refund);
        $this->assign('order_info', $order_info);
        $this->assign('order_goods', $order_goods);
        $this->display();
    }

    /*
     * 提交退款
     * 1.返回买家消费积分
     * 2.按比例扣除商品奖励积分
     * 3.更改订单状态
     * 4.更新订单各项商品数据
     * 5.更新退款日志表
     * 6.添加订单状态日志
     */
    public function refund_submit() {
        // print_r($_POST);
        // exit;
        $order_id = $this->_postid('order_id');
        $note     = $this->_post('note');   //财务备注
        $actual_refund = $this->_post('actual_refund');     //实际退款数组
        $actual_return = $this->_post('actual_return');     //实际退货数组
        $score_minus   = $this->_post('score_minus');       //扣除结邻币数组

        $refund_total = array_sum($actual_refund);  //退款总金额
        $return_total = array_sum($actual_return);  //退货总数量
        $score_minus_total = array_sum($score_minus);   //扣除结邻币总数


        //退款订单
        $order_info = M('order')
            ->field('`user_id`,`order_sn`,`shipping_fee`,`score_used`,`goods_amount`,`return_amount`')
            ->where(array('id'=>$order_id))
            ->find();
        //按退款比例退还结邻币
        $score_return = floor($refund_total/$order_info['goods_amount']*$order_info['score_used']);
        
        //检查用户结邻币是否足够
        $user_score = M('user')
            ->field('`shopping_credit`')
            ->where(array('uid'=>$order_info['user_id']))
            ->find();

        $user_score = $user_score['shopping_credit'] + $score_return - $score_minus_total;
        if($user_score < 0) {
            $this->JsonReturn('用户积分不足', null, 0);
            exit;
        } else {    //增减积分
            if($score_return > 0) {
                D('shopScore')->setUserScore($score_return, 1, $order_info['user_id'], $order_info['order_sn'], '退款返还 订单号：');
            }
            if($score_minus_total > 0) {
                D('shopScore')->setUserScore($score_minus_total, 0, $order_info['user_id'], $order_info['order_sn'], '退款扣除 订单号：');
            }
        }

        //是否退还邮费
        if(isset($_POST['return_shipping_fee']) && $_POST['return_shipping_fee']==1) {
            $refund_shipping = $order_info['shipping_fee'];
        } else {
            $refund_shipping = 0;
        }
        
        //更新订单状态
        M('order')->update(
            array(
                'finish_time'     => time(),
                'refund_shipping' => $refund_shipping,
                'actual_refund'   => $refund_total+$refund_shipping,
                'actual_return'   => $return_total,
                'order_state'     => $order_info['return_amount'] ? 71 : 70,  //已退货OR已退款
                'score_return'    => $score_return,
            ),
            array('id'=>$order_id)
        );

        

        //退款商品
        $order_goods = M('order_goods')
            ->field('`id`')
            ->where(" `order_id`=$order_id AND `goods_refund`>0 ")
            ->findAll();

        //更新order_goods
        foreach ($order_goods as $v) {
            $k = $v['id'];
            M('order_goods')->update(
                array(
                    'actual_refund' => $actual_refund[$k],
                    'actual_return' => $actual_return[$k],
                    'score_minus'   => $score_minus[$k],
                ),
                array('id'=>$k)
            );
        }


        //更新退款日志
        M('return_log')->update(
            array(
                'finance_id'    => admin::$adminInfo['id'],
                'actual_refund' => $refund_total+$refund_shipping,
                'actual_return' => $return_total,
                'finance_msg'   => $note,
                'finance_time'  => time(),
                'refund_state'  => 4,      //财务已退款
            ),
            array('order_id'=>$order_id)
        );

        //添加订单日志
        $order_state = $order_info['return_amount'] ? 71 : 70;
        D('order')->log($order_id, $order_state, $note, 'admin-'.admin::$adminInfo['id']);

        $this->JsonReturn('提交成功', null, 1);
    }
}